#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time   :2018/7/4 11:28
# @Author :huchao
# @E_mail :gmclqb@163.com
# @QQ : 九零九一三零零八三
# 功能描述：模块用来向微信服务器请求登录用户的数据
import json
import ssl
from urllib import request
# import requests


class WXLogin:
    appid = 'wxb07b77039e001a16'
    secret= 'b731cbafbf3ff81b4b84c973cc304e37'
    grant_type= 'authorization_code'
    js_code= ''
    url = 'https://api.weixin.qq.com/sns/jscode2session'

    def __init__(self):
        self.session_key = None
        self.openid = None

    def __call__(self, code=None, *args, **kwargs):
        if code:
            self.js_code = code
        self.get_user_openid()
        return self.session_key,self.openid

    def get_user_openid(self):
        '''用来获取用户openid'''

        # self.data = requests.get(self.url,params=self.wx_data)
        # https://api.weixin.qq.com/sns/jscode2session?
        # appid=APPID&secret=SECRET&
        # js_code=JSCODE&
        # grant_type=authorization_code
        url = self.url + "?appid={}&secret={}&js_code={}&grant_type={}".format(
            self.appid,self.secret,self.js_code,self.grant_type)
        ssl._create_default_https_context = ssl._create_unverified_context
        req = request.Request(url=url, method='GET')
        with request.urlopen(req) as res:
            data = res.read().decode('utf8')
            if data.find('errcode') == -1:
                data = data.lstrip('{').rstrip('}').split(',')
                dic = dict()
                for d in data:
                    dic.update({str(d.split(':')[0].lstrip('"').rstrip('"')):d.split(':')[1].strip('"')})
                print(dic,type(dic))
                self.session_key = dic.get('session_key')
                self.openid = dic.get('openid')
            else:
                raise ValueError('微信服务器请求参数错误')


if __name__ == '__main__':
    code = '1231231231231313123123123'
    wx = WXLogin()
    print(wx())
